import { ref, reactive, watch } from 'vue'
import { ElMessage } from 'element-plus'
import { CustomerSourceSelector as CustomerSourceSelect } from '@/components/business/customer'
import { CustomerGradeSelector as CustomerGradeSelect } from '@/components/business/customer'
import { CustomerStatusSelector as CustomerStatusSelect } from '@/components/business/customer'
import { RegionCascader } from '@/components/business/region'
import { AdminSelector, UserDepartmentSelector } from '@/components/business/user'
import { customerApi } from '@/api/customer'

// 表单引用
const formRef = ref()

// 客户表单数据
const customerForm = reactive({
  customer_type: 16, // 默认企业客户
  name: '',
  source_id: '',
  tax_num: '',
  provinceid: '',
  cityid: '',
  distid: '',
  address: '',
  customer_status: '',
  grade_id: '',
  belong_name: '', // 管家姓名
  belong_uid: '', // 管家ID
  belong_did: '', // 管家部门ID
  belong_department: '', // 管家部门名称
  creator_name: '', // 录入人姓名
  creator_id: '', // 录入人ID
  share_names: '',
  share_uids: '',
  contact_name: '',
  contact_mobile: '',
  contact_email: '',
  contact_wechat: '',
  contact_qq: '',
  contact_gender: 1, // 1:男, 2:女
  description: '',
  group_code: '', // 客户分组代码
  is_primary: 1, // 是否主客户(0:否, 1:是) - 默认设为主客户
  controller_name: '', // 负责人姓名
  relation_desc: '', // 客户关系描述
})

// 地区级联数据 - 改为 string 类型以适配新组件
const regionData = ref<string>('')

// 处理地区选择变化
const handleRegionChange = (value: string | string[] | null, selectedOptions: any[]) => {
  console.log('地区选择变化:', value, selectedOptions)
  if (value) {
    // 确保selectedOptions是数组类型
    const optionsArray = Array.isArray(selectedOptions) ? selectedOptions : [selectedOptions]

    // 根据selectedOptions来获取完整的省市区信息
    if (optionsArray && optionsArray.length > 0) {
      // 如果有选择路径，从中提取省市区ID
      const province = optionsArray[0]
      const city = optionsArray.length > 1 ? optionsArray[1] : null
      const district = optionsArray.length > 2 ? optionsArray[2] : null

      customerForm.provinceid = province?.id || ''
      customerForm.cityid = city?.id || ''
      customerForm.distid = district?.id || ''
    } else {
      // 如果没有选择路径，使用value作为区县ID
      if (Array.isArray(value)) {
        customerForm.distid = value[value.length - 1] || ''
      } else {
        customerForm.distid = value
      }
    }
  } else {
    customerForm.provinceid = ''
    customerForm.cityid = ''
    customerForm.distid = ''
  }
}

// 监听地区数据变化
watch(
  () => [customerForm.provinceid, customerForm.cityid, customerForm.distid],
  ([provinceid, cityid, distid]) => {
    // 如果有完整的省市区数据，则更新regionData
    if (provinceid && cityid && distid) {
      // 新组件需要完整的路径字符串，格式为 "省份代码/城市代码/区县代码"
      regionData.value = `${provinceid}/${cityid}/${distid}`
    } else if (provinceid && cityid) {
      regionData.value = `${provinceid}/${cityid}`
    } else if (provinceid) {
      regionData.value = provinceid
    } else {
      regionData.value = ''
    }
  },
  { immediate: true }
)

// 监听管家ID变化
watch(
  () => customerForm.belong_uid,
  newValue => {
    if (newValue && adminList.value.length > 0) {
      // 当管家ID改变时，更新管家相关信息
      const selectedAdmin = adminList.value.find(admin => String(admin.id) === String(newValue))
      if (selectedAdmin) {
        console.log('选中的管家信息:', selectedAdmin)
        customerForm.belong_name = selectedAdmin.name || ''
        if (selectedAdmin.department) customerForm.belong_department = selectedAdmin.department
        if (selectedAdmin.did) customerForm.belong_did = selectedAdmin.did
      } else {
        console.warn('未找到匹配的管家信息，ID:', newValue)
      }
    } else if (!newValue) {
      // 清空管家相关字段
      customerForm.belong_name = ''
      customerForm.belong_department = ''
      customerForm.belong_did = ''
    }
  }
)

// 表单验证规则
const rules = {
  name: [{ required: true, message: '请输入客户名称', trigger: 'blur' }],
  source_id: [{ required: true, message: '请选择客户来源', trigger: 'change' }],
  tax_num: [{ required: true, message: '请输入证件号码', trigger: 'blur' }],
  grade_id: [{ required: true, message: '请选择客户等级', trigger: 'change' }],
  address: [{ required: true, message: '请输入详细地址', trigger: 'blur' }],
  contact_name: [{ required: true, message: '请输入联系人姓名', trigger: 'blur' }],
  contact_mobile: [
    { required: true, message: '请输入联系电话', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' },
  ],
  contact_email: [{ type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }],
  // 新增字段的验证规则
  controller_name: [{ required: false, message: '请输入负责人姓名', trigger: 'blur' }],
  relation_desc: [{ required: false, message: '请输入客户关系描述', trigger: 'blur' }],
}

// 用户列表
const userList = ref<any[]>([])

// 用户选择弹窗可见性
const userDialogVisible = ref(false)

// 管理员列表数据
const adminList = ref<any[]>([])

// 用户选择弹窗可见性
const userSelectorVisible = ref(false)

// 是否在选择录入人
const isSelectingCreator = ref(false)

// 返回上一页 - 由抽屉控件直接处理
const goBack = (emit: any) => {
  emit('cancel')
}

// 选择录入人
const selectCreator = () => {
  isSelectingCreator.value = true
  userSelectorVisible.value = true
}

// 选择管家
const selectUser = () => {
  isSelectingCreator.value = false
  userSelectorVisible.value = true
}

// 选择共享员工
const selectSharedUsers = () => {
  // 实现共享员工选择逻辑
  ElMessage.info('选择共享员工功能待实现')
}

// 处理用户选择完成
const handleUserSelected = (user: any) => {
  if (isSelectingCreator.value) {
    // 设置为录入人 - 始终使用name字段
    customerForm.creator_name = user.name
    customerForm.creator_id = user.id
  } else {
    // 设置为管家
    customerForm.belong_name = user.name
    customerForm.belong_uid = user.id
    customerForm.belong_did = user.did
    customerForm.belong_department = user.department
  }
}

// 提交表单
const submitForm = async (emit: any) => {
  if (!formRef.value) return

  formRef.value.validate(async (valid: boolean) => {
    if (valid) {
      try {
        // 根据是否主客户设置提交数据，同时添加contacts数组格式
        const submitData = {
          ...customerForm,
          // 主客户的group_code由后端生成，前端设为空
          group_code: customerForm.is_primary === 1 ? '' : customerForm.group_code,
          // 将平铺的联系人信息转换为后端期望的contacts数组格式
          contacts: [
            {
              name: customerForm.contact_name || '',
              mobile: customerForm.contact_mobile || '',
              email: customerForm.contact_email || '',
              wechat: customerForm.contact_wechat || '',
              qq: customerForm.contact_qq || '',
              gender: customerForm.contact_gender || 1,
            },
          ],
        }

        console.log('提交客户数据:', submitData)
        // 调用customerApi的addCustomer方法提交数据
        const response = await customerApi.addCustomer(submitData)

        if (response.code === 0) {
          ElMessage.success('新增客户成功')
          // 从响应中获取客户ID，而不是从submitData
          const customerId = response.data?.id
          emit('submit', customerId)
        } else {
          ElMessage.error(response.msg || '新增客户失败')
        }
      } catch (error) {
        console.error('提交客户数据失败:', error)
        ElMessage.error((error as Error).message || '新增客户失败')
      }
    }
  })
}

// 初始化数据
const init = async () => {
  // 获取当前用户信息并设置为默认录入人
  try {
    const userInfo = JSON.parse(localStorage.getItem('userInfo') || '{}')
    if (userInfo && userInfo.id) {
      // 优先使用name字段，如果没有则使用nickname或username
      customerForm.creator_name = userInfo.name || userInfo.nickname || userInfo.username || ''
      customerForm.creator_id = userInfo.id
    }

    // 加载管理员列表
    await loadAdminList()
  } catch (error) {
    console.error('初始化数据失败:', error)
  }
}

// 加载管理员列表
const loadAdminList = async () => {
  try {
    const response = await customerApi.getAdminList()
    console.log('获取管理员列表响应:', response)

    // 直接处理原始响应数据
    const responseData = response as any // 使用any类型避免类型错误
    if (responseData && responseData.code === 0) {
      // 统一处理不同的响应格式
      let adminData = []

      // 处理直接返回数组的情况
      if (Array.isArray(responseData.data)) {
        console.log('API返回数据直接是数组，长度:', responseData.data.length)
        adminData = responseData.data
      }
      // 处理返回带有list字段的情况
      else if (responseData.data && Array.isArray(responseData.data.list)) {
        console.log('API返回数据包含list字段，列表长度:', responseData.data.list.length)
        adminData = responseData.data.list
      }

      // 更新管理员列表，增强数据映射逻辑
      adminList.value = adminData.map((item: any) => ({
        id: item.id,
        name: item.name || item.username || item.nickname || `管理员${item.id}`,
        department: item.department || '',
        did: item.did || '',
      }))

      console.log('管理员列表数据加载成功:', adminList.value)
    } else {
      ElMessage.error(responseData?.msg || '获取管理员列表失败')
    }
  } catch (error) {
    console.error('获取管理员列表失败:', error)
  }
}

// 导出所有需要在模板中使用的变量和方法
export {
  // 响应式数据
  formRef,
  customerForm,
  regionData,
  rules,
  userList,
  userDialogVisible,
  adminList,
  userSelectorVisible,
  isSelectingCreator,

  // 方法
  goBack,
  selectCreator,
  selectUser,
  selectSharedUsers,
  handleUserSelected,
  submitForm,
  init,
  handleRegionChange,
}
